require('dotenv').config();
const OSS = require('ali-oss');

console.log('[OSS] 初始化配置:');
console.log('  region:', 'oss-cn-wulanchabu');
console.log('  bucket:', 'yton');
console.log('  accessKeyId:', !!process.env.OSS_ACCESS_KEY_ID ? '[已设置]' : '[未设置]');
console.log('  accessKeySecret:', !!process.env.OSS_ACCESS_KEY_SECRET ? '[已设置]' : '[未设置]');

const client = new OSS({
  region: 'oss-cn-wulanchabu',
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  bucket: 'yton',
  secure: true,
});

// 上传 buffer
async function uploadBuffer(buffer, key) {
  console.log(`[OSS] 开始上传文件: ${key}`);
  try {
    const result = await client.put(key, buffer);
    console.log('[OSS] 上传成功:', result.name);
    return result.name;
  } catch (error) {
    console.error('[OSS] 上传失败:', error);
    throw error;
  }
}

// 生成签名 URL
function getSignedUrl(key) {
  const url = client.signatureUrl(key, { expires: 3600 });
  console.log(`[OSS] 生成签名URL: ${url}`);
  return url;
}

module.exports = {
  uploadBuffer,
  getSignedUrl,
};
